<template>
  <div id="app">
    <router-view />
  </div>
</template>
<script>
let socket = 0
let alarmer = null
const notice = []
const ENV = process.env.NODE_ENV
import { mapState } from 'vuex'
export default {
  name: 'App',
  created() {
    try {
      setTimeout(function() {
        document.getElementById('app').style.display = 'block'
      }, 500)
    } catch (e) {}
  },
  computed: {
    ...mapState({
      userId: state => state.userInfo.id
    })
  },

  mounted() {
    this.$nextTick(() => {
      const loading = document.querySelector('#loading')
      if (loading) {
        document.body.removeChild(loading)
      }
    })
  },

  methods: {
    // 推送发生报警事件
    createWs() {
      const pathname = window.location.pathname
      if (pathname === '/login') {
        return false
      }
      if (!this.userId) {
        return false
      }
      const vm = this
      // let ws_url = 'ws://123.59.136.8:8081/ws' // 线上推送
      // let ws_url = 'ws://192.168.1.154:8081/ws' // 测试服务器推送
      // let ws_url = 'ws://192.168.1.90:8081/ws'  //本地推送

      let ws_url = 'ws://192.168.1.231:8081/ws' // 大众

      // if (ENV === 'production') {
      //   ws_url = 'ws://123.59.136.8:8081/ws'
      // }

      ws_url = ws_url + `/${vm.userId}`

      if ('WebSocket' in window) {
        socket = 1
        const ws = (vm.ws = new WebSocket(ws_url))
        ws.onopen = () => console.log(`websocket 已连接`)
        ws.onmessage = message => {
          let { data } = message
          data = JSON.parse(data)
          // console.log(data)
          if ('closeId' in data) {
            this.closeNotice(data.closeId)
          } else {
            if (!alarmer) {
              alarmer = vm.$alarm()
            }
            data['len'] = notice.length + 1
            data['callback'] = vm.removeNoticeCallback
            const n = vm.$notice(data)
            notice.push(n)
          }
        }

        ws.onclose = () => {
          console.log('ws 连接已关闭')
          socket = 0
          if (alarmer) {
            alarmer.close()
          }
        }
      }
    },

    // 移除notice回调
    removeNoticeCallback({ id }) {
      const index = notice.findIndex(t => t.id === id)
      if (index > -1) {
        notice.splice(index, 1)
        notice.forEach(t => (t.content.len = notice.length))
        if (notice.length === 0 && alarmer) {
          alarmer.close()
          alarmer = null
          return
        }
      }
    },

    // 处理报警
    closeNotice(closeId) {
      const ids = closeId.map(t => 'notice-' + t)
      const item = ids.map(t => {
        return notice.find(n => n.id === t)
      })
      if (item && item.length > 0) {
        item.forEach(t => {
          if (t) {
            t.close()
          }
        })
      }
    }
  },
  watch: {
    $route() {
      if (socket === 1) {
        return false
      }
      this.createWs()
    }
  }
}
</script>
